package com.lgmshare.k3.ui.upgrade;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;

import com.lgmshare.component.downloader.SimpleFileDownloader;
import com.lgmshare.k3.K3Config;
import com.lgmshare.k3.ui.dialog.DialogUtils;
import com.lgmshare.component.utils.ContextUtils;
import com.lgmshare.component.utils.FileUtils;

import java.io.File;
import java.text.DecimalFormat;


/**
 * 下载更新界面
 */
public class UpgradeDownloadManger {

    private static final int MSG_DOWNLOAD_SIZE = 10001;
    private static final int MSG_DOWNLOAD_SUCCESS = 10003;
    private static final int MSG_DOWNLOAD_FAIL = 10004;

    private Context mContext;
    private String mDownloadUrl;

    private ProgressDialog mProgressDialog;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DOWNLOAD_SUCCESS:
                    //下载成功，开始安转
                    String filePath = msg.getData().getString("filepath");
                    processDownloadSuccess(filePath);
                    break;
                case MSG_DOWNLOAD_FAIL:
                    String errorMsg = msg.getData().getString("error_msg");
                    processDownloadFail(errorMsg);
                    break;
                case MSG_DOWNLOAD_SIZE:
                    double size = msg.getData().getLong("size");
                    double loaded = msg.getData().getLong("loaded");
                    double progress = loaded / size;
                    mProgressDialog.setProgress((int) (progress * 100));
                    mProgressDialog.setProgressNumberFormat(String.format("%s / %s", formatFileSize((long) size), formatFileSize((long) loaded)));
                    break;
                default:
                    break;
            }
        }
    };

    public UpgradeDownloadManger(Context context, String downloadUrl) {
        mContext = context;
        mDownloadUrl = downloadUrl;
    }

    private String formatFileSize(long size) {
        String str;
        DecimalFormat df = new DecimalFormat("######0.00");
        Double dm = Double.valueOf(size) / (1024d * 1024d);
        Double dk = Double.valueOf(size) / 1024d;
        if (dm > 0) {
            str = df.format(dm) + "mb";
        } else {
            str = df.format(dk) + "kb";
        }
        return str;
    }

    /**
     * 下载成功，执行安装
     */
    private void processDownloadSuccess(String filePath) {
        dismissDownloadProgressDialog();
        ContextUtils.installApk(mContext, filePath);
    }

    /**
     * 下载失败
     */
    private void processDownloadFail(String errorMsg) {
        dismissDownloadProgressDialog();
        Dialog dlg = DialogUtils.createSimpleOkCancelDialog(mContext, "去下载", new OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(mDownloadUrl);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                mContext.startActivity(it);
            }
        }, "确定", new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }, "文件下载失败", "下载安装包失败，请使用浏览器访问地址下载最新版本。");
        dlg.setCancelable(false);
        dlg.show();
    }

    /**
     * 开始下载更新包
     */
    public void startDownloadApk() {
        showDownloadProgressDialog("正在下载安装包，请稍候...");
        try {
            final String filename = "test.apk";
            final String url = mDownloadUrl;
            SimpleFileDownloader.get().start(url, FileUtils.getInternalDirPath(mContext, K3Config.FILE_DIR_DOWNLOAD), "app.apk", new SimpleFileDownloader.OnFileDownloadListener() {

                @Override
                public void onStart() {

                }

                @Override
                public void onFinish() {

                }

                @Override
                public void onCancel() {

                }

                @Override
                public void onProgress(long totalSize, long currentSize, long offset) {
                    Message msg = new Message();
                    msg.what = MSG_DOWNLOAD_SIZE;
                    msg.getData().putLong("size", totalSize);
                    msg.getData().putLong("loaded", currentSize);
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onSuccess(File file) {
                    Message msg = new Message();
                    msg.what = MSG_DOWNLOAD_SUCCESS;
                    msg.getData().putString("filepath", file.getAbsolutePath());
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onFailure(String errorMsg) {
                    Message msg = new Message();
                    msg.what = MSG_DOWNLOAD_FAIL;
                    msg.getData().putString("error_msg", "下载失败");
                    mHandler.sendMessage(msg);
                }
            });

            /*DownloadTask task = new DownloadTask.Builder(url, FileUtils.getDiskFilePath(mContext, "apk"), filename)
                    // the minimal interval millisecond for callback progress
                    .setMinIntervalMillisCallbackProcess(800)
                    // ignore the same task has already completed in the past.
                    .setPassIfAlreadyCompleted(false)
                    .build();
            task.enqueue(new DownloadListener4WithSpeed() {

                private long totalLength;

                @Override
                public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                    totalLength = info.getTotalLength();
                }

                @Override
                public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {

                }

                @Override
                public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                    Message msg = new Message();
                    msg.what = MSG_DOWNLOAD_SIZE;
                    msg.getData().putLong("size", totalLength);
                    msg.getData().putLong("loaded", currentOffset);
                    mHandler.sendMessage(msg);
                }

                @Override
                public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {

                }

                @Override
                public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
                    switch (cause) {
                        case ERROR: {
                            Message msg = new Message();
                            msg.what = MSG_DOWNLOAD_FAIL;
                            msg.getData().putString("error_msg", realCause.getMessage());
                            mHandler.sendMessage(msg);
                        }
                        break;
                        case COMPLETED: {
                            //安装包下载成功
                            Message msg = new Message();
                            msg.what = MSG_DOWNLOAD_SUCCESS;
                            msg.getData().putString("filepath", task.getFile().getAbsolutePath());
                            mHandler.sendMessage(msg);
                        }
                        break;
                    }
                }

                @Override
                public void taskStart(@NonNull DownloadTask task) {

                }

                @Override
                public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {

                }

                @Override
                public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {

                }
            });*/
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.obtainMessage(MSG_DOWNLOAD_FAIL).sendToTarget();
        }
    }

    /**
     * 进度窗口
     */
    private void showDownloadProgressDialog(String content) {
        try {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setTitle("升级中");
            mProgressDialog.setMessage(content);
            mProgressDialog.setProgress(0);
            mProgressDialog.setMax(100);
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissDownloadProgressDialog() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}